package fourfaith.com.ff_sl21_app;

import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.List;

import fourfaith.com.ff_sl21_app.adapter.ReplaceViewPager;
import fourfaith.com.ff_sl21_app.fragment.ReportDetailFragment;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;

public class ReportInfoActivity extends AppCompatActivity implements ReportDetailFragment.OnFragmentInteractionListener{

    private TabLayout mTabLayout;
    private ReplaceViewPager mViewPager;
    private List<Fragment> list_fragment;
    private FragmentManager manager;
    private ReportDetailFragment mServer;
    private LayoutInflater mInflater;
    private ImageView back;
    private static String stcd = null, stnm=null;
    private Integer dsfl;

    private ImageView state;
    private TextView siteName;
    int titleLength = 0;
    //tablayout的标题
   // private String[] mTitles = new String[]{"水位","雨量","电压","信号强度","库上水位","库下水位","温度","湿度","ph","风速","风向","盐度",};
    private String[] mTitles;
    private String[] flags;
    private LinearLayout progressBarChar, dataErrorChar, dataEmptyChar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_info);
        stcd = getIntent().getStringExtra("stcd");
        stnm = getIntent().getStringExtra("stnm");
        dsfl = getIntent().getIntExtra("deviceStatus", 0);
        getDataList();

    }
    public void initView(){
        mTabLayout = (TabLayout)findViewById(R.id.id_tablayout);
        mViewPager = (ReplaceViewPager)findViewById(R.id.id_viewpager);
        back = (ImageView)findViewById(R.id.back);
        state = (ImageView)findViewById(R.id.state);
        siteName = (EditText)findViewById(R.id.siteName);
        mViewPager.setScanScroll(false);
        mInflater = LayoutInflater.from(this);

        progressBarChar = (LinearLayout)findViewById(R.id.progressBarChar);
        dataErrorChar = (LinearLayout)findViewById(R.id.dataErrorChar);
        dataEmptyChar = (LinearLayout)findViewById(R.id.dataEmptyChar);

        siteName.setText(stnm);
        state.setImageResource((Integer)dsfl);

        list_fragment = new ArrayList<>();
        if(titleLength>0){
            showDataPage();
            for(int i =1;i<= titleLength;i++){
                mServer = new ReportDetailFragment();
                Bundle args = new Bundle();
                args.putString("stcd", stcd);
                args.putString("flag", flags[i-1]);
                mServer.setArguments(args);
                list_fragment.add(mServer);
            }
        }else{
            showEmptyPage();
        }
        initEven();
    }
    public void initEven(){
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //viewPager通过适配器与fragment关联
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return list_fragment.get(position);
            }
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }

            @Override
            public int getCount() {
                return list_fragment.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitles[position];
            }
        });
        //TabLayout和ViewPager的关联
       // mViewPager.setOffscreenPageLimit(list_fragment.size());
        mTabLayout.setupWithViewPager(mViewPager);
    }
    /**
     * 数据加载失败显示错误页面
     */
    public void showErrorPage() {
        progressBarChar.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
        dataErrorChar.setVisibility(View.VISIBLE);
        dataEmptyChar.setVisibility(View.GONE);
    }

    /**
     * 数据加载中页面
     */
    public void showLoadingPage() {
        progressBarChar.setVisibility(View.VISIBLE);
        dataErrorChar.setVisibility(View.GONE);
        dataEmptyChar.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
    }

    /**
     * 数据页面
     */
    public void showDataPage() {
        progressBarChar.setVisibility(View.GONE);
        dataErrorChar.setVisibility(View.GONE);
        mViewPager.setVisibility(View.VISIBLE);
        dataEmptyChar.setVisibility(View.GONE);
    }

    /**
     * 空数据页面
     */
    public void showEmptyPage() {
        progressBarChar.setVisibility(View.GONE);
        dataErrorChar.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
        dataEmptyChar.setVisibility(View.VISIBLE);
    }
    public void getDataList(){
        String userId = Constants.getUserId();
        String url = Constants.allFactorByStcd +"?userId=" + userId + "&stcd="+stcd;

        RequestQueue mQueue = RequestQueueSingleton.getInstance(this).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {
                        JSONObject dataObj =(JSONObject)responseResult.getData();
                        int objContent = dataObj.size();
                        int i =0;
                        if(objContent>0){
                            mTitles = new String[dataObj.size()];
                            flags = new String[dataObj.size()];
                            for(java.util.Map.Entry<String,Object> entry:dataObj.entrySet()){
                                String keyString = entry.getKey();//提取key
                                if(!keyString.equals("")){
                                    boolean exist = dataObj.containsKey(keyString);
                                    if(exist){
                                        JSONObject obj =  dataObj.getJSONObject(keyString);
                                        String stnm = obj.getString("name");
                                        String flag = obj.getString("flag");
                                        mTitles[i] = stnm;
                                        flags[i] =flag;
                                        i=i+1;
                                    }
                                }
                            }
                        }else{
                            mTitles = new String[]{""};
                        }
                        titleLength = i;
                        //mTitles[i+1] = "水位";
                        initView();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error.networkResponse == null) {
                    Toast.makeText(ReportInfoActivity.this, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(ReportInfoActivity.this, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ReportInfoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        });
        mQueue.add(jsonRequest);

    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}
